<template>
  <div ref="mainLinS" id="mainLin"></div>
</template>

<script lang="ts" setup>
import { onMounted, onBeforeUnmount, ref } from 'vue';
import * as echarts from 'echarts';

const mainLinS = ref();
let myChart: echarts.ECharts | null = null;

type EChartsOption = echarts.EChartsOption;
const option: EChartsOption = {
  title: {
    text: ''
  },
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['Email', 'Union Ads', 'Video Ads', 'Direct', 'Search Engine']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  toolbox: {
    feature: {
      saveAsImage: {}
    }
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: 'Email',
      type: 'line',
      stack: 'Total',
      data: [120, 132, 101, 134, 90, 230, 210]
    }
  ]
};

const resizeHandler = new ResizeObserver(() => {
  if (myChart) {
    myChart.resize();
  }
});

onMounted(() => {
  if (mainLinS.value) {
    myChart = echarts.init(mainLinS.value);
    myChart.setOption(option);
    resizeHandler.observe(mainLinS.value);
  }
  // 备选方案：监听窗口大小变化
  window.addEventListener('resize', () => {
    if (myChart) {
      myChart.resize();
    }
  });
});

onBeforeUnmount(() => {
  if (mainLinS.value) {
    resizeHandler.unobserve(mainLinS.value);
  }
  // 移除窗口大小变化监听器
  window.removeEventListener('resize', () => {
    if (myChart) {
      myChart.resize();
    }
  });
});
</script>

<style lang="scss" scoped>
#mainLin {
  width: 100%;
  height: 300px;
}
</style>